#define  _CRT_SECURE_NO_WARNINGS
class Solution {
public:
    int maxProfit(int k, vector<int>& prices) {
        int n = prices.size();
        k = min(n / 2, k);
        vector<vector<int>> buy(n, vector<int>(k + 1));
        auto sold = buy;
        for (int i = 1; i <= k; i++) buy[0][i] = -0x3f3f3f;
        buy[0][0] = -prices[0];
        for (int i = 1; i < n; i++)
        {
            for (int d = 0; d < k; d++)
            {
                buy[i][d] = max(buy[i - 1][d], sold[i - 1][d] - prices[i]);
                sold[i][d + 1] = max(sold[i - 1][d + 1], buy[i - 1][d] + prices[i]);
            }
        }
        int ret = sold[n - 1][0];
        for (int i = 1; i <= k; i++) ret = max(sold[n - 1][i], ret);
        return ret;
    }
};